package com.notetool.util.config;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConfigPath
{
    
    ////////////////////
    // Members
    private ArrayList<String> tokens;

    ////////////////////
    // Constructors
    public ConfigPath (ArrayList<String> path)
    {
        tokens = path;
    }
    
    ////////////////////
    // Public static methods
    public static ConfigPath fromString (String path)
    {
        // Validate String
        Pattern pattern = Pattern.compile("[ ]*([/]{1})?((((~?[\\w\\*\\-_]+)|[\\.]{1}|[\\.]{2})([/]{1}((~?[\\w\\*\\-_]+)|[\\.]{1}|[\\.]{2}))*)/?)?[ ]*");
        Matcher matcher = pattern.matcher(path);
        
        if (!matcher.matches())
            throw new InvalidPathException ();
        
        // Split path and instantiate object
        String strippedPath = matcher.group(3);
        ConfigPath newPath = new ConfigPath (splitString (strippedPath));
        
        return newPath;
    }
    
    ////////////////////
    // Private static methods
    private static ArrayList<String> splitString (String path)
    {
        ArrayList<String> pathTokens = new ArrayList<String> ();
        
        // No path no tokens!
        if (path == null)
            return pathTokens;
        
        // Cut String till we're out of separators (/)
        while (path.length () > 0)
        {
            // Find next separator
            int index = path.indexOf ('/');
            
            // If no separator, then add remaining path as token and finish
            if (index == -1)
                index = path.length();
            
            // Extract token and add to list if not empty
            String token = path.substring(0, index);
            
            if (token.length () > 0)
                pathTokens.add (token);
            
            // remove from path
            path = path.substring (index >= path.length () ? index : index + 1);
        }
        
        return pathTokens;
    }
    
    ////////////////////
    // Public methods
    public boolean isEmpty ()
    {
        return tokens.isEmpty ();
    }
    
    public String pullToken ()
    {
        return tokens.remove(0);
    }
    
}
